package com.wecommodule.bpm.ext.biz.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.HttpMethod;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class HttpUtils {
    public static String sendGet(String url) throws IOException {
        log.info("=================send get request:{}", url);
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod(HttpMethod.GET);
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.info(response.toString());
            return response.toString();
        } else {
            log.info("GET request not worked. responseCode:" + responseCode + "\nURL:\n"+ url);
        }
        return "";
    }

    public static String sendPostWithBody(String url, JSONObject param) {
        BufferedReader reader = null;
        HttpURLConnection con = null;
        try {
            URL restUrl = new URL(url);
            // 打开和URL之间的连接
            con = (HttpURLConnection)restUrl.openConnection();
            //请求post方式
            con.setRequestMethod("POST");
            // Post请求不能使用缓存
            con.setUseCaches(false);
            // 设置是否从HttpURLConnection输入，默认值为 true
            con.setDoInput(true);
            // 设置是否使用HttpURLConnection进行输出，默认值为 false
            con.setDoOutput(true);

            //设置header内的参数 connection.setRequestProperty("健, "值");
            con.setRequestProperty("Content-Type", "application/json");

            // 建立实际的连接
            con.connect();

            // 得到请求的输出流对象
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
            writer.write(param.toString());
            writer.flush();

            // 获取服务端响应，通过输入流来读取URL的响应
            InputStream is = con.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            // 打印读到的响应结果
            return sbf.toString();
        }catch (Exception e) {
            log.info("发送 POST 请求出现异常！url:{}", url, e);
        }finally {
            try {
                if(reader != null) {
                    reader.close();
                }
            }catch (IOException ex){
                log.info("关闭BufferedReader异常：", ex);
            }

            // 关闭连接
            if(con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送 POST 请求出现异常！url:{}", url, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
